package com.bootdo.system.controller;

import com.bootdo.common.constant.RoleConstant;
import com.bootdo.common.controller.BaseController;
import com.bootdo.common.utils.*;
import com.bootdo.system.domain.DeptDO;
import com.bootdo.system.domain.ScoreLogDO;
import com.bootdo.system.domain.UserDO;
import com.bootdo.system.domain.WeekDO;
import com.bootdo.system.service.DeptService;
import com.bootdo.system.service.ScoreLogService;
import com.bootdo.system.service.WeekService;
import com.bootdo.system.vo.ScoreLogVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 扣分记录
 *
 * @author zhouxm
 * @date 2021-01-15 10:32:59
 */

@Controller
@RequestMapping("/system/score")
@Slf4j
public class ScoreLogController extends BaseController {
    private String prefix = "system/score";

    @Autowired
    private ScoreLogService logService;

    @Autowired
    private DeptService deptService;

    @Autowired
    private ScoreLogService scoreLogService;

    @Autowired
    private WeekService weekService;

    @GetMapping()
    @RequiresPermissions("system:score:log")
    public String scoreLog(){
        return prefix + "/log";
    }

    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("system:score:log")
    public PageUtils list(@RequestParam Map<String, Object> params){
        /*UserDO user = ShiroUtils.getUser();
        if (user.getRoleIds().contains(RoleConstant.ROLE_HEAD_MASTER)) {
            params.put("deptId", user.getDeptId());
        }*/
        if(StringUtils.isEmpty((String) params.get("createdTimeStart")) && StringUtils.isEmpty((String) params.get("createdTimeEnd"))) {
            //获取当前时间属于第几周
            String strDateFormat = "yyyy-MM-dd";
            SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
            String queryDate = sdf.format(new Date());
            params.put("queryDate",queryDate);
            WeekDO weekDO = weekService.getWeekDetail(params);
            if(null != weekDO && null != weekDO.getWeekStartDate() && null != weekDO.getWeekEndDate()) {
                params.put("createdTimeStart", sdf.format(weekDO.getWeekStartDate()) + " 00:00:00");
                params.put("createdTimeEnd", sdf.format(weekDO.getWeekEndDate()) + " 23:59:59");
            }
        }

        setDateQuery(params);
        //查询列表数据
        Query query = new Query(params);
        List<ScoreLogVO> logList = new ArrayList<>();
        int total = 0;
        try {
            logList = logService.list(query);
            total = logService.count(query);
        } catch (Exception e) {
            log.error("获取列表出错：", e);
        }
        return new PageUtils(logList, total);
    }

    @GetMapping("/add")
    @RequiresPermissions("system:score:add")
    String add(){
        return prefix + "/add";
    }

    @GetMapping("/edit/{id}")
    @RequiresPermissions("system:score:edit")
    String edit(@PathVariable("id") String id,Model model){
        ScoreLogVO score = new ScoreLogVO();
        try {
            score = logService.get(id);
        } catch (Exception e) {
            log.error("获取详情出错：", e);
        }
        model.addAttribute("attachId", UUID.randomUUID());
        model.addAttribute("log", score);
        return prefix + "/edit";
    }

    @GetMapping("/detail/{id}")
    String detail(@PathVariable("id") String id,Model model){
        ScoreLogVO score = new ScoreLogVO();
        try {
            score = logService.get(id);
        } catch (Exception e) {
            log.error("获取详情出错：", e);
        }
        model.addAttribute("attachId", UUID.randomUUID());
        model.addAttribute("log", score);
        return prefix + "/detail";
    }

    @GetMapping("/verify/{id}")
    @RequiresPermissions("system:score:verify")
    String verify(@PathVariable("id") String id,Model model){
        ScoreLogVO score = new ScoreLogVO();
        try {
            score = logService.get(id);
        } catch (Exception e) {
            log.error("获取详情出错：", e);
        }
        model.addAttribute("attachId", UUID.randomUUID());
        model.addAttribute("log", score);
        return prefix + "/verify";
    }

    /**
     * 保存
     */
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("system:score:add")
    public R save( ScoreLogDO score){
        try {
            if(logService.save(score)>0){
                return R.ok();
            }
        } catch (Exception e) {
            log.error("保存出错：", e);
        }
        return R.error();
    }
    /**
     * 修改
     */
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("system:score:edit")
    public R update( ScoreLogDO score){
        try {
            UserDO userDO = new UserDO();
            userDO.setUserId(ShiroUtils.getUserId());
            logService.update(score,userDO);
        } catch (Exception e) {
            log.error("更新出错：", e);
            return R.error();
        }
        return R.ok();
    }

    /**
     * 管理员编辑打分评价
     * @param scoreLogDO
     * @return
     * @throws Exception
     */
    @ResponseBody
    @PostMapping("/updateScore")
    public R updateScore(ScoreLogDO scoreLogDO) throws Exception {
        ScoreLogVO scoreLogVO = scoreLogService.get(scoreLogDO.getId());
        DeptDO dept = deptService.get(scoreLogDO.getDeptId());
        //修改先减去之前评价的分数在加上重新修改的分数
        dept.setScore(dept.getScore() - scoreLogVO.getScore() +scoreLogDO.getScore());
        deptService.update(dept);
        scoreLogDO.setUpdatedBy(ShiroUtils.getUserId());
        scoreLogDO.setUpdatedTime(new Date());
        scoreLogService.updateScore(scoreLogDO);
        return R.ok();
    }

    /**
     * 打分评价审核
     * @param scoreLogDO
     * @return
     */
    @ResponseBody
    @RequestMapping("/check")
    public R check(HttpServletRequest request, ScoreLogDO scoreLogDO) throws Exception {
        UserDO userDO = new UserDO();
        userDO.setUserId(ShiroUtils.getUserId());
        logService.update(scoreLogDO,userDO);
        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping( "/remove")
    @ResponseBody
    @RequiresPermissions("system:score:remove")
    public R remove( String id){
        try {
            if(logService.remove(id)>0){
                return R.ok();
            }
        } catch (Exception e) {
            log.error("删除出错：", e);
        }
        return R.error();
    }

    /**
     * 删除
     */
    @PostMapping( "/batchRemove")
    @ResponseBody
    @RequiresPermissions("system:score:batchRemove")
    public R remove(@RequestParam("ids[]") String[] ids){
        try {
            logService.batchRemove(ids);
        } catch (Exception e) {
            log.error("批量删除出错：", e);
            return R.error();
        }
        return R.ok();
    }

}
